package pers.vic.basics.leetcode;

import com.sun.org.apache.bcel.internal.generic.LRETURN;

import javax.swing.*;
import java.nio.channels.Pipe;

/**
 * @author Vic.xu
 * @description:2. 两数相加
 * 给出两个 非空 的链表用来表示两个非负的整数。其中，它们各自的位数是按照 逆序 的方式存储的，并且它们的每个节点只能存储 一位 数字。
 * <p>
 * 如果，我们将这两个数相加起来，则会返回一个新的链表来表示它们的和。
 * <p>
 * 您可以假设除了数字 0 之外，这两个数都不会以 0 开头。
 * <p>
 * 输入：(2 -> 4 -> 3) + (5 -> 6 -> 4)
 * 输出：7 -> 0 -> 8
 * 原因：342 + 465 = 807
 * @date: 2020/10/28 0028 17:43
 */
public class J0002_M_AddTwoNumbers {
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        //需要返回的结果
        ListNode res = null;
        //当前位和节点
        ListNode cur = null;

        //同位数之和
        int sum = 0;
        //进位
        int carry = 0;

        while (l1 != null || l2 != null || carry !=0) {
            sum = carry;
            if (l1 != null) {
                sum += l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                sum += l2.val;
                l2 = l2.next;
            }
            carry = sum / 10;
            sum = sum % 10;

            if (cur == null) {
                cur = new ListNode(sum);
                res = cur;
            } else {
                cur.next = new ListNode(sum);
                cur = cur.next;
            }
        }
        return res;
    }

    public static void main(String[] args) {

        ListNode l1 = build(9999999);

        ListNode l2 = build(9999);
        print(l1);
        print(l2);

        ListNode res = addTwoNumbers(l1, l2);

        print(res);


    }

    // 个位→十位→百位→千位....
    public static ListNode build(int num) {
        if (num == 0) {
            return new ListNode(num);
        }
        ListNode res = null;
        ListNode cur = null;
        while (num != 0) {
            //当前位数
            int val = num % 10;
            num = num / 10;
            if (cur == null) {
                cur = new ListNode(val);
                res = cur;
            }else {
                cur.next = new ListNode(val);
                cur = cur.next;
            }
        }
        System.out.println(num + ": ");
        print(res);
        return res;
    }

    public static void print(ListNode node) {
        ListNode n = node;
        while (n != null) {
            System.out.print(n.val + "→");
            n = n.next;
        }
        System.out.println();
    }

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}